﻿using System.IO;
using System.Windows.Forms;
using System.Text;

namespace Layers.UI
{


    public class TextBoxWriter : TextWriter
    {
        private TextBox _tbOutput;
        private StringBuilder _buffer;
        private bool _needFlush;
        private Timer _timer;

        public TextBoxWriter(TextBox tb)
        {
            _tbOutput = tb;
            _buffer = new StringBuilder();
            _timer = new Timer();
            _timer.Tick += new System.EventHandler(Timer_Tick);
            _timer.Interval = 1000;
            _timer.Start();
        }

        void Timer_Tick(object sender, System.EventArgs e)
        {
            if(_needFlush)
                Flush();
        }

        public override void Write(char[] buffer, int index, int count)
        {
            int nlIdx = System.Array.IndexOf(buffer, '\n', index, count);
            _buffer = _buffer.Append(buffer, index, count);
            _needFlush = true;
            FlushIfNeeded();
        }

        public override void Write(char ch)
        {
            _buffer.Append(ch);
            _needFlush = true;
            FlushIfNeeded();
        }

        private void FlushIfNeeded()
        {
            //if (_needFlush)
             //     Flush();
        }

        private void Flush()
        {
            _tbOutput.AppendText(_buffer.Replace("\n", "\r\n").ToString());
            _buffer = new StringBuilder();
            _needFlush = false;
        }

        public override Encoding Encoding
        {
            get { return null; }
        }
    }

}